<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Brand;
use App\Http\Model\Car;
use App\Http\Model\CarConfig;
use App\Http\Model\Carinfo;
use App\Http\Model\CarModel;
use App\Http\Model\Store;
use App\Http\Model\Taocan;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;


class CarController extends CommonController
{
    //get.admin/car  汽车列表页
    public function index(){
        //将汽车表、汽车配置表和汽车详情表关联起来
        $data = Car::all();
        return view('admin.car.index',compact('data'));
    }

    //upload 异步上传列表图片
    public function upload(){
        $file = Input::file('Filedata');
        if($file->isValid()){
            $entension = $file->getClientOriginalExtension();//上传文件后缀名
            $newName = date('YmdHis').mt_rand(100,999).'.'.$entension;//重组文件名
            $path = $file -> move(base_path().'/uploads',$newName);//移动到存放上传文件的文件夹
            $filepath = 'uploads/'.$newName;
            return $filepath;
        }
    }


    //get. Admin/car/create  汽车增加页面
    public function create(){
        //获得品牌数据
        $brand = Brand::all();
        //获得车型数据
        $carmodel = CarModel::all();
        //获得门店数据
        $store = Store::all();

        //载入页面,分配数据
        return view('admin.car.add',compact('brand','carmodel','store'));
    }

    //post.admin/car 添加汽车提交
    public function store(){
        $input = Input::all();

        //验证规则
        $rules = [
            'carname'=>'required',
        ];

        $message = [
            'carname.required'=>'汽车名称不能为空',
        ];

        $validator = Validator::make($input,$rules,$message);

        if($validator->passes()){
            //重组汽车表数据
            $carData = [
                'carname'=>$input['carname'],
                'cprice'=>$input['cprice'],
                'listView'=>$input['listView'],
                'hot'=>$input['hot'],
                'count'=>$input['count'],
                'carID'=>$input['carID'],
                'sendtime'=>time(),
                'zc_carModel_mid'=>$input['zc_carModel_mid'],
                'zc_brand_bid'=>$input['zc_brand_bid'],
                'zc_store_menid'=>$input['zc_store_menid'],
            ];
            $car = Car::create($carData);//向汽车表添加数据

            $car_id = $car['attributes']['id'];//获取添加进汽车表的id主键

            //向中间表填充数据
            $taocan = DB::table('taocan')->lists('tid');//获得套餐表的主键id
            //循环该数组，向中间表添加数据
            foreach($taocan as $k=>$v){
                DB::table('car_has_zc_taocan')->insert([
                    'zc_taocan_tid' => $v,
                    'zc_car_id' => $car_id,
                ]);
            }


            //重组汽车配置表的数据
            $configData = [
                'cm'=>$input['cm'],
                'zw'=>$input['zw'],
                'rylx'=>$input['rylx'],
                'bsx'=>$input['bsx'],
                'px'=>$input['px'],
                'rybh'=>$input['rybh'],
                'qdfs'=>$input['qdfs'],
                'fdjjq'=>$input['fdjjq'],
                'tc'=>$input['tc'],
                'yxrl'=>$input['yxrl'],
                'yx'=>$input['yx'],
                'zy'=>$input['zy'],
                'dcld'=>$input['dcld'],
                'qn'=>$input['qn'],
                'DvD'=>$input['DvD'],
                'GPS'=>$input['GPS'],
                'car_id'=>$car_id,
            ];

            CarConfig::create($configData);//向汽车配置表中添加数据

            //获得异步上传的汽车详情图
            $bigimgs = $input['bigimg'];

            //循环数组
            foreach ($bigimgs as $k=>$v){
                $this->makeThumb($v,'uploads/thumb_'.basename($v),0,118,64);
                //小图路径
                $smallimgs[] = 'uploads/thumb_'.basename($v);
            }

            //将小图路径转换为字符串
            $smallimgs =  implode(',',$smallimgs);

            //转换为字符串
            $bigimgs = implode(',',$bigimgs);

            //重组汽车信息表的信息
            $infoData = [
                'bigimg'=>$bigimgs,
                'smallimg'=>$smallimgs,
                'car_id'=>$car_id,
            ];
            //向汽车详情表写入数据
            $re = Carinfo::create($infoData);

            if($re){
                return redirect('admin/car');
            }else{
                return back()->with('errors','数据添加失败');
            }
        }else{
            return back()->withErrors($validator);
        }

    }

    //get.admin/car/{car}/edit  编辑文章
    public function edit($id)
    {
        //获得品牌数据
        $brand = Brand::all();
        //获得车型数据
        $carmodel = CarModel::all();
        //获得门店数据
        $store = Store::all();

        $data = DB::table('car')
           ->join('carconfig', 'id', '=', 'carconfig.car_id')
           ->join('carinfo', 'id', '=', 'carinfo.car_id')
           ->find($id);
        $data->bigimg = explode(',',$data->bigimg);//将bigimg字段中的字符串转换为数组

        return view('admin.car.edit',compact('data','brand','carmodel','store'));
    }

    //put.admin/car/{car}    更新文章
    public function update($id)
    {
        $input = Input::all();
//        dd($input);

        //重组汽车表数据
        $carData = [
            'carname'=>$input['carname'],
            'cprice'=>$input['cprice'],
            'listView'=>$input['listView'],
            'hot'=>$input['hot'],
            'count'=>$input['count'],
            'carID'=>$input['carID'],
            'sendtime'=>time(),
            'zc_carModel_mid'=>$input['zc_carModel_mid'],
            'zc_brand_bid'=>$input['zc_brand_bid'],
            'zc_store_menid'=>$input['zc_store_menid'],
        ];
        Car::where('id',$id)->update($carData);

        //获得汽车配置表的主键id
        $fid = CarConfig::where('car_id',$id)->value('fid');

        //重组汽车配置表的数据
        $configData = [
            'cm'=>$input['cm'],
            'zw'=>$input['zw'],
            'rylx'=>$input['rylx'],
            'bsx'=>$input['bsx'],
            'px'=>$input['px'],
            'rybh'=>$input['rybh'],
            'qdfs'=>$input['qdfs'],
            'fdjjq'=>$input['fdjjq'],
            'tc'=>$input['tc'],
            'yxrl'=>$input['yxrl'],
            'yx'=>$input['yx'],
            'zy'=>$input['zy'],
            'dcld'=>$input['dcld'],
            'qn'=>$input['qn'],
            'DvD'=>$input['DvD'],
            'GPS'=>$input['GPS'],
            'car_id'=>$id,
        ];

        CarConfig::where('fid',$fid)->update($configData);//更新汽车配置表里的数据

        //获得汽车详情表的主键id
        $cid = Carinfo::where('car_id',$id)->value('cid');

        //获得异步上传的汽车详情图
        $bigimgs = $input['bigimg'];

        //循环数组
        foreach ($bigimgs as $k=>$v){

                $this->makeThumb($v,'uploads/thumb_'.basename($v),0,118,64);

            //小图路径
            $smallimgs[] = 'uploads/thumb_'.basename($v);
        }

        //将小图路径转换为字符串
        $smallimgs =  implode(',',$smallimgs);

        //转换为字符串
        $bigimgs = implode(',',$bigimgs);

        $oldBigimg = Carinfo::where('cid',$cid)->value('bigimg');
        if($oldBigimg == $bigimgs){
            $re = true;
        }else{
            //重组汽车信息表的信息
            $infoData = [
                'bigimg'=>$bigimgs,
                'smallimg'=>$smallimgs,
                'car_id'=>$id,
            ];

            $re = Carinfo::where('cid',$cid)->update($infoData);//更新汽车配置表里的数据
        }


        if($re){
            return redirect('admin/car');
        }else{
            return back()->with('errors','文章更新失败，请稍后重试！');
        }
    }

    //delete.admin/car/{car}   删除单个文章
    public function destroy($id)
    {
        //获得汽车配置表的主键id
        $fid = CarConfig::where('car_id',$id)->value('fid');
        //获得汽车详情表的主键Id
        $cid = Carinfo::where('car_id',$id)->value('cid');

        //删除汽车表数据
        Car::where('id',$id)->delete();
        //删除中间表数据
        DB::table('car_has_zc_taocan')->where('zc_car_id',$id)->delete();
        //删除汽车配置表
        CarConfig::where('fid',$fid)->delete();
        //删除汽车详情表
       $re =  Carinfo::where('cid',$cid)->delete();
        if($re){
            $data = [
                'status' => 0,
                'msg' => '文章删除成功！',
            ];
        }else{
            $data = [
                'status' => 1,
                'msg' => '文章删除失败，请稍后重试！',
            ];
        }
        return $data;
    }

    //缩略图函数
    public function makeThumb($ori_img, $new_img, $percent=50, $width=0, $height=0){

        $original = getimagesize($ori_img); //得到图片的信息，可以print_r($original)发现它就是一个数组
        //$original[2]是图片类型，其中1表示gif、2表示jpg、3表示png
        switch($original[2]){
            case 1 : $s_original = imagecreatefromgif($ori_img);
                break;
            case 2 : $s_original = imagecreatefromjpeg($ori_img);
                break;
            case 3 : $s_original = imagecreatefrompng($ori_img);
                break;
        }

        if($percent > 0){
            $width = $original[0] * $percent / 100;
            $width = ($width > 0) ? $width : 1;
            $height = $original[1] * $percent / 100;
            $height = ($height > 0) ? $height : 1;
        }

        //创建一个真彩的画布
        $canvas = imagecreatetruecolor($width,$height);
        imagecopyresized($canvas, $s_original, 0, 0, 0, 0, $width, $height, $original[0], $original[1]);
        //header("Content-type:image/jpeg");
        //imagejpeg($canvas); //向浏览器输出图片
        $loop = imagejpeg($canvas, $new_img); //生成新的图片
    }
}
